package editor.menu;

import java.awt.Graphics;
import java.util.LinkedList;
import java.util.List;

import applet.resource.Sprite0D;


/** */
public class JumpList {
	/** */
	private static final Sprite0D TOP_SPRITE = new Sprite0D(
			"editor/jump-list/top.png");
	/** */
	private static final Sprite0D BOTTOM_SPRITE = new Sprite0D(
			"editor/jump-list/bottom.png");
	/** */
	private static final Sprite0D SEPARATOR_SPRITE = new Sprite0D(
			"editor/jump-list/separator.png");
	/** */
	private static final Sprite0D ITEM_SPRITE = new Sprite0D(
			"editor/jump-list/item.png");

	/** */
	private static final int SEPARATOR_HEIGHT = 4;

	/** */
	private int index;
	/** */
	private List<JumpListItem> items;

	/**
	 * @param newIndex
	 *            - the position of the jump list.
	 */
	public JumpList(final int newIndex) {
		index = newIndex;
		items = new LinkedList<JumpListItem>();
	}

	/** @return the position of this jump list. */
	public final int getIndex() {
		return index;
	}

	/** @return the height of this jump list. */
	public final int getHeight() {
		int height = 2 * SEPARATOR_HEIGHT;
		for (JumpListItem item : items) {
			if (item instanceof Separator) {
				height += SEPARATOR_HEIGHT;
			} else if (item instanceof Item) {
				height += Item.HEIGHT;
			}
		}
		return height;
	}

	/**
	 * @param item
	 *            - the item to add.
	 */
	public final void addItem(final JumpListItem item) {
		items.add(item);
	}

	/**
	 * @param item
	 *            - the item to remove.
	 */
	public final void removeItem(final JumpListItem item) {
		items.remove(item);
	}

	/**
	 * @param g
	 *            - the graphics context to draw to.
	 */
	public final void draw(final Graphics g) {
		final int posX = index * Item.WIDTH;
		int posY = Menu.Y;

		posY -= SEPARATOR_HEIGHT;
		BOTTOM_SPRITE.draw(g, posX, posY);

		for (JumpListItem item : items) {
			if (item instanceof Separator) {
				posY -= SEPARATOR_HEIGHT;
				SEPARATOR_SPRITE.draw(g, posX, posY);
			} else if (item instanceof Item) {
				posY -= Item.HEIGHT;
				ITEM_SPRITE.draw(g, posX, posY);
				((Item) item).draw(g, posX, posY);
			}
		}

		posY -= SEPARATOR_HEIGHT;
		TOP_SPRITE.draw(g, posX, posY);
	}

	/**
	 * @param y
	 *            - the y position of the item.
	 * @return the item.
	 */
	public final Item getItem(final int y) {
		int posY = Menu.Y;
		if (y >= posY) {
			return null;
		}
		for (JumpListItem item : items) {
			if (item instanceof Separator) {
				posY -= SEPARATOR_HEIGHT;
				if (y >= posY) {
					return null;
				}
			} else if (item instanceof Item) {
				posY -= Item.HEIGHT;
				if (y >= posY) {
					return (Item) item;
				}
			}
		}
		return null;
	}
}
